package com.xcity.util;

import java.util.Arrays;
import java.util.Objects;

public class ExpCalculator {

	private int[] exps; // 每级所需经验（累计）
	
	public ExpCalculator(int maxLevel) {
		exps = new int[maxLevel + 1];
	}
	
	public ExpCalculator(int[] exps) {
		this.exps = Objects.requireNonNull(exps);
	}
	
	public void setAndSum(int level, int exp) {
		exps[level] = exp + (level > 0 ? exps[level - 1] : 0);
	}
	
	public int getMaxLevel() {
		return exps.length - 1;
	}
	
	/**
	 * 累计经验 - 当前等级所需的累计经验
	 * @param level
	 * @param totalExp
	 * @return
	 */
	public int getCurrentLevelExp(int level, int totalExp) {
		int maxLvl = getMaxLevel();
		if (level >= maxLvl) {
			return exps[maxLvl];
		}
		int val = totalExp - exps[level];
		return val;
	}
	
	/**
	 * 获取该等级所需非累计经验
	 * @param level
	 * @return
	 */
	public int getExp(int level) {
		if (level < 0 || level > getMaxLevel()) {
			level = getMaxLevel();
		}
		int val = exps[level];
		if (level > 0) {
			val -= exps[level - 1];
		}
		return val;
	}
	
	/**
	 * 到达该等级所需累计经验
	 * @param level
	 * @return
	 */
	public int getTotalExp(int level) {
		return level >= 0 && level <= getMaxLevel() ? exps[level] : exps[getMaxLevel()];
	}
	
	public int exp2Lvl(int exp) {
		for (int i = 0; i < exps.length; i++) {
			if (exp < exps[i]) {
				return i - 1;
			}
		}
		return getMaxLevel();
	}

	@Override
	public String toString() {
		return Arrays.toString(exps);
	}
	
}
